package chapter17;

import org.junit.Test;

import java.util.*;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/11/28 10:49
 */
public class CollectionTest01 {
    @Test
    public void testUnsupported() {
        List<String> list = Arrays.asList("a b c d e f g h i j k".split(" "));
        test("Modifiable copy", new ArrayList<>(list));
        test("Arrays.asList()", list);
        test("unmodifiableList()", Collections.unmodifiableList(new ArrayList<>(list)));
    }

    @Test
    public void testSortedSet() {
        SortedSet<String> sortedSet = new TreeSet<>();
        Collections.addAll(sortedSet, "one two three four five six seven eight nine ten".split(" "));
        System.out.println(sortedSet);

        String low = sortedSet.first();
        String high = sortedSet.last();
        System.out.println(low);
        System.out.println(high);

        Iterator<String> iterator = sortedSet.iterator();
        for (int i = 0; i <= 6; i++) {
            if (i == 3) {
                low = iterator.next();
            } else if (i == 6) {
                high = iterator.next();
            } else {
                iterator.next();
            }
        }

        System.out.println(low);
        System.out.println(high);

        System.out.println(((TreeSet<String>) sortedSet).subSet(low, high));
        System.out.println(((TreeSet<String>) sortedSet).headSet(high));
        System.out.println(((TreeSet<String>) sortedSet).tailSet(low));
    }

    private void test(String msg, List<String> list) {
        System.out.println("-----" + msg + "------");
        Collection<String> c = list;
        Collection<String> sublist = list.subList(1, 3);
        Collection<String> c2 = new ArrayList<>(sublist);
        try {
            c.retainAll(c2);
        } catch (Exception e) {
            System.out.println("retainAll():" + e);
        }

        try {
            c.removeAll(c2);
        } catch (Exception e) {
            System.out.println("removeAll():" + e);
        }

        try {
            c.clear();
        } catch (Exception e) {
            System.out.println("clear():" + e);
        }

        try {
            c.add("x");
        } catch (Exception e) {
            System.out.println("add():" + e);
        }

        try {
            c.addAll(c2);
        } catch (Exception e) {
            System.out.println("addAll():" + e);
        }

        try {
            c.remove(c.iterator().next());
        } catch (Exception e) {
            System.out.println("remove():" + e);
        }

        try {
            list.set(0, "X");
        } catch (Exception e) {
            System.out.println("set():" + e);
        }
    }
}
